import { submit, allList, list, roleList, query, down, importAccount, exportData, del} from './activityRulesListServ';
import $ from 'jquery';
// 弹出消息框
import { message } from 'antd'
import { parse } from 'qs'
import { download } from 'utils/util'
/* isEmpty 对象是否为空
 * cloneDeep 对象深拷贝
 */
import { cloneDeep } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const state = {
    paramCode: 'SECONDARY_BROKER_CONFIG',
    chooseFlag: false,
    ustdvisibe: false,
    exportLoading: false,
    chooseData: [],
    imageUrls: [],
    idlist:[],
    addform:{},
    createTime:null,
    
    detail: {
        noDevelopSecoBrok: {
            mideazyStaff: 1,    //美的置业员工 0否1是
            frontLineSales: 1,  //一线销售 0否1是
            loginSetTime: 180,   //多少天内登陆过的用户
            designatedUser: 0   //指定用户 0否1是
        },
        //有效期设置:
        termOfValiditySet: [
            // { idType: '1', termOfValidity: 12 },  //身份类型编码 100  有效期天数100
        ],
        //有效期续期方式:
        renewalMethods: [
            {   //二级经纪人推荐客户
                renewalMethod: null, //二级经纪人推荐客户
                renewalDaysConf: null,  //按有效期顺延或 
                // fixedDays: '',  //固定天数
                // renewalNum: ''  //可续期次数
            },
            {   // 邀请二级经纪人续期 
                renewalMethod: null,  // 邀请二级经纪人续期 
                renewalDaysConf: null, //按有效期顺延或
                // fixedDays: '',   //固定天数
                // renewalNum: ''   //可续期次数
            }
        ],
        sceBrokTitleImgs: [],
        sceBrokPosterImgs: [],
        shareWechatImgs:[],
        activityRules: "活动规则"


    },
    other:null,
    num: 1,   //图片计数
    key: null,
    roleType: null,
    // 分页
    detailsPageNo: '',
    detailsPageSize: '',
    detailsTotal: "",
}

const tmpModule = {
    // namespace: 'secondaryBrokerConfig',
    state: cloneDeep(state),
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                if ('' + tmpModule.pathname === '' + pathname) {
                    // dispatch({ type: 'allList', payload: {} });
                    dispatch({ type: 'list', payload: {} });
                    dispatch({ type: 'getRoleList', payload: {} });
                
                }
            })
        },
    },
    effects: {
        //测试数据接口
        * allList({ payload }, { put, call, select }) {
            try {
                //admin/coupons/config/list
                const { data, success } = yield call(allList, {});
                if (success) {
                    if (data) {
                        yield put({ type: 'updateStore', payload: { detail: data } });
                    }
                }
            } catch (e) { }
        },
        //获取身份
        *getRoleList({ payload }, { call, put, select }){
            let { detail } = yield select(state => state[tmpModule.namespace])
            const { success,rows} = yield call(roleList)
            if(success){
                let agentList = []
                rows.map((item,index)=>{
                    let obj={}
                    obj.id = item.roleId
                    obj.name = item.name
                    if(detail.termOfValiditySet.length) {
                        detail.termOfValiditySet.forEach(i =>{
                            if(item.roleId === i.idType){
                                obj.disabled = true
                            }
                        })
                    }
                    agentList.push(obj)
                })
                yield put({
                    type: 'updateStore', payload: {
                        agentList: agentList
                    }
                })
            }
        },
        //获取用户管理列表
        *getuser({ payload }, { call, put, select }){
            let { addform } = yield select(state => state[tmpModule.namespace])
            let params = {
                ...addform,
                pageNo: payload.pageNo || 1,
                pageSize:payload.pageSize || 10
            }
            let data = yield call(query, {...params})
            if(data.success){
                
                yield put({
                    type: 'updateStore', payload: {
                        chooseData: data.rows,
                        detailsPageNo:data.pageNo,
                        detailsPageSize: data.pageSize,
                        detailsTotal: data.total,
                    }
                })
            }
        },
        // 获取列表数据
        * list({ payload }, { put, call, select }) {
            try {
                console.log(false == 0);
                //admin/coupons/config/list
                const { data, success } = yield call(list, {});
                if (success) {
                    let quer = JSON.parse(data.paramValue)
                    quer.renewalMethods.forEach(i =>{
                        if(i.renewalDaysConf ==='TERM_OF_VALIDITY'){
                            i.renewalDaysConf = 1
                        }else{
                            i.renewalDaysConf = 2
                        }
                    })
                    let listdata = []
                    let other = null
                    quer.termOfValiditySet.forEach(i => {
                        if(i.idType!=="other"){
                            listdata.push(i)
                        } else {
                            other = i.termOfValidity
                        }
                    })
                    quer.termOfValiditySet = listdata
                    yield put({ type: 'updateStore', payload: { detail: quer, num:3-quer.sceBrokPosterImgs.length, other:other} });
                    yield put({ type: 'getRoleList', payload: {}});

                }
            } catch (e) { }
        },
        //导出模板
        * down ({payload}, {put, call, select}) {
            try {
              const {data, success} = yield call(down)
              yield put({type: 'updateStore', payload: {exportLoading: false}})
              if (success) {
                let url = data.url || ''
                if (url) {
                  download(url)
                }
              }
            } catch (e) {
              console.error(e)
            }
        },
        // 导出数据
        * exportData ({payload}, {put, call, select}) {
            let { idlist } = yield select(state => state[tmpModule.namespace])
            if(!idlist.length){
                return message.error('未选中数据');
            }
            let params = {
                IllegalBrokerInviteIds: idlist
            }
            try {
              const {data, success} = yield call(exportData, {...params})
              yield put({type: 'updateStore', payload: {exportLoading: false}})
              if (success) {
                var $a = $("<a>");
                $a.attr("href", data.href);
                $a.attr("download", data.download);
                $("body").append($a);
                $a[0].click();
                $a.remove();
                //   download(data.href)
                // window.open(data.url)
                
              }
            } catch (e) {
              console.error(e)
            }
        },
        // 上传表格
        * importAccount ({payload}, {put, call, select}) {
            let { imageUrls } = yield select(state => state[tmpModule.namespace])
            let fileUrl = imageUrls.length ? imageUrls[0].url : null
            if (!fileUrl) {
              message.error('请上传文件')
              return false
            }
            let params = {
                aliOssFileUrl: fileUrl,
            }
            try {
              const {data, success, msg} = yield call(importAccount, {...params})
              if (success === true) {
                message.success('操作成功')
                yield put({ type: 'updateStore', payload: { ustdvisibe: false } });
                yield put({ type: 'getuser', payload: {} });
              }
            } catch (e) {
              message.error(msg)
              return false
            }
            // yield put({ type: 'updateStore', payload: {uploadFileObj}});
          },
        //重置查询
        *onReset ({ }, { put }) {
            yield put({ type: 'updateStore', payload: { addform: {} } });
            yield put({ type: 'getuser', payload: {} });
            
        },
        // 二级经纪人移除
        *del ({payload}, { put, call, select}) {
            let { idlist } = yield select(state => state[tmpModule.namespace])
            if(!idlist.length){
                return message.error('未选中数据');
            }
            let params = {
                illegalBrokerInviteIds: idlist
            }
            try {
              const {data, success} = yield call(del, {...params})
              if (success) {
                // yield put({ type: 'updateStore', payload: {  data } });
                yield put({ type: 'getuser', payload: {}});
                message.success('移除成功')
              }
            } catch (e) {
              console.error(e)
            }
            
        },
        // 图片删除
        * updateModel({ payload }, { put, select }) {
            // message.success('成功删除')
            yield put({ type: 'updateStore', payload });
        },
        // 单选框
        * updateRadio({ payload }, { put, select }) {
            yield put({ type: 'updateStore', payload })
        },

        // 提交
        * submit({ payload }, { put, call, select }) {
           console.log(payload,'提交数据')
            try {
                const { data, success } = yield call(submit, payload);
                if (success) {

                    message.success('保存成功');
                }
            } catch (e) { }
        },

    },

    // 存入状态机
    reducers: {
        updateStore(preState, action) {
            return { ...preState, ...action.payload };
        }
    }
}

export default tmpModule